<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span
          v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
          class="no-redirect"
          >{{ item.meta.title }}</span
        >
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

interface RouteItem {
  path: string
  meta: {
    title: string
    breadcrumb?: boolean
  }
  redirect?: string
  name?: string
  children?: RouteItem[]
  matched?: RouteItem[]
}

// 定义响应式数据
const levelList = ref<RouteItem[]>([])
const route = useRoute()
const router = useRouter()
const store = useStore()

// 获取面包屑
const getBreadcrumb = () => {
  // only show routes with meta.title
  let matched: RouteItem[] = []
  const pathNum = findPathNum(route.path)

  // multi-level menu
  if (pathNum > 2) {
    const reg = /\/\w+/gi
    const pathMatches = route.path.match(reg)
    if (pathMatches) {
      const pathList = pathMatches.map((item, index) => {
        if (index !== 0) item = item.slice(1)
        return item
      })
      getMatched(pathList, store.getters.defaultRoutes, matched)
    }
  } else {
    matched = route.matched.filter((item) => item.meta && item.meta.title) as unknown as RouteItem[]
  }

  // 判断是否为首页
  if (!isDashboard(matched[0])) {
    matched = [{ path: '/index', meta: { title: '首页' } }].concat(matched)
  }

  levelList.value = matched.filter(
    (item) => item.meta && item.meta.title && item.meta.breadcrumb !== false,
  )
}

// 查找路径中的分隔符数量
const findPathNum = (str: string, char = '/'): number => {
  let index = str.indexOf(char)
  let num = 0
  while (index !== -1) {
    num++
    index = str.indexOf(char, index + 1)
  }
  return num
}

// 获取匹配的路由
const getMatched = (pathList: string[], routeList: RouteItem[], matched: RouteItem[]) => {
  const data = routeList.find(
    (item) =>
      item.path == pathList[0] || (item.name && item.name.toString().toLowerCase()) == pathList[0],
  )

  if (data) {
    matched.push(data)
    if (data.children && pathList.length) {
      pathList.shift()
      getMatched(pathList, data.children, matched)
    }
  }
}

// 判断是否为仪表盘
const isDashboard = (routeItem: RouteItem | undefined): boolean => {
  const name = routeItem && routeItem.name
  if (!name) {
    return false
  }
  return name.trim() === 'Index'
}

// 处理链接点击
const handleLink = (item: RouteItem) => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect)
    return
  }
  router.push(path)
}

// 监听路由变化
watch(
  () => route,
  (newRoute) => {
    // if you go to the redirect page, do not update the breadcrumbs
    if (newRoute.path.startsWith('/redirect/')) {
      return
    }
    getBreadcrumb()
  },
  { immediate: true },
)

// 组件挂载时获取面包屑
onMounted(() => {
  getBreadcrumb()
})
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
